import { Socket, io } from 'socket.io-client';

// 定义连接选项接口
interface SocketConnectionOptions {
    url?: string;
    path?: string;
    extraHeaders?: Record<string, string>;
    query?: Record<string, any>;
    transports?: string[];
    autoConnect?: boolean;
    reconnection?: boolean;
    reconnectionAttempts?: number;
    reconnectionDelay?: number;
    timeout?: number;
}

// 定义SocketIO服务接口
interface SocketIOService {
    socket: Socket | null;
    connect(token: string, options?: Partial<SocketConnectionOptions>): Socket;
    on(event: string, callback: (...args: any[]) => void): void;
    emit(event: string, data: any): void;
    disconnect(): void;
}

const SocketService: SocketIOService = {
    socket: null,

    connect(token: string, options: Partial<SocketConnectionOptions> = {}): Socket {
        const url = options.url || 'http://your-server.com';

        // 使用options设置请求头
        this.socket = io(url, {
            extraHeaders: {
                'Authorization': `Bearer ${token}`,
                ...(options.extraHeaders || {})
            },
            query: {
                token: token,
                ...(options.query || {})
            },
            path: options.path,
            // 其他配置
            transports: options.transports || ['websocket'],
            autoConnect: options.autoConnect !== undefined ? options.autoConnect : true,
            reconnection: options.reconnection !== undefined ? options.reconnection : false,
            reconnectionAttempts: options.reconnectionAttempts || 5,
            reconnectionDelay: options.reconnectionDelay || 1000,
            timeout: options.timeout || 20000
        });

        this.socket.on('connect', () => {
            console.log('Socket.IO连接已建立');
        });

        this.socket.on('disconnect', (reason: string) => {
            console.log('Socket.IO连接已断开:', reason);
        });

        this.socket.on('connect_error', (error: Error) => {
            console.error('Socket.IO连接错误:', error);
        });

        return this.socket;
    },

    on(event: string, callback: (...args: any[]) => void): void {
        if (this.socket) {
            this.socket.on(event, callback);
        } else {
            console.warn('Socket.IO未初始化，无法添加事件监听器');
        }
    },

    emit(event: string, data: any): void {
        if (this.socket) {
            this.socket.emit(event, data);
        } else {
            console.error('Socket.IO未连接，无法发送事件');
        }
    },

    disconnect(): void {
        if (this.socket) {
            this.socket.disconnect();
            this.socket = null;
        }
    }
}

export default SocketService;
